<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="注册/登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-form
      @submit="onLogin"
      :show-error="false"
      :show-error-message="false"
      @failed="onfailed"
      ref="login-form"
    >
      <van-field
        name="mobile"
        v-model="user.mobile"
        icon-prefix="iconfont"
        left-icon="iconfont icon-zhanghaodenglu"
        placeholder="请输入手机号"
        center
        :rules="formRules.mobile"
        :validate-first="true"
      />
      <van-field
        name="code"
        v-model="user.code"
        clearable
        center
        icon-prefix="iconfont"
        left-icon="iconfont icon-mima"
        placeholder="验证码"
        :rules="formRules.code"
      >
        <template #button>
          <van-count-down
            :time="1000 * 60"
            format="ss 秒"
            v-if="isCountDownShow"
            @finish="isCountDownShow = false"
          />
          <van-button
            class="send-btn"
            size="mini"
            v-else
            round
            :loading="isSendSmsLoading"
            @click.prevent="onSendSms"
          >
            发送验证码
          </van-button>
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button
          class="login-btn"
          type="info"
          block
        >
          登录
        </van-button>
      </div>
    </van-form >
  </div>
</template>

<script>
import { login, SendSms } from '@/api/user.js'
import { Toast } from 'vant'

export default {
  name: 'LoginIndex',
  components: {},
  data () {
    return {
      user: {
        mobile: '17090086870', // 手机号
        code: '246810' // 验证码
      },
      // 表单的验证规则
      formRules: {
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '手机号格式错误' }
        ],
        code: [
          { required: true, message: '请输入验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式错误' }
        ]
      },
      // 控制倒计时是否显示
      isCountDownShow: false,
      // 控制 Loading 按钮是否显示
      isSendSmsLoading: false
    }
  },
  methods: {
    onClickLeft () {
      this.$router.back()
    },
    // 登录
    async onLogin () {
      Toast.loading({
        message: '登录中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const { data } = await login(this.user)
        Toast.success('登录成功')
        // 将后端返回的 token 数据放到 Vuex 容器中
        this.$store.commit('setUser', data.data)
        // 清除路由的缓存
        this.$store.commit('removeCachePages', 'LayoutIndex')
        // 登录成功后，返回上一层
        // this.$router.back()
        this.$router.push(this.$route.query.redirect || '/')
      } catch (err) {
        Toast.fail('请检查手机号或验证码是否正确')
      }
    },
    // 提交表单且验证不通过后触发
    onfailed (err) {
      if (err.errors[0]) {
        Toast(err.errors[0])
      }
    },
    // 发送验证码
    async onSendSms () {
      let message = ''
      try {
        // 校验手机号码
        await this.$refs['login-form'].validate('mobile')
        // 在未成功发送短信前，显示 loading
        this.isSendSmsLoading = true
        // 手机号校验通过后，调用接口，服务器端发送短信验证码
        await SendSms(this.user.mobile)
        // 短信发送成功后，显示倒计时
        this.isCountDownShow = true
        Toast('发送成功')
      } catch (err) {
        if (err && err.response && err.response.status === 429) {
          message = '发送频繁，请稍后重试'
        } else if (err.name === 'mobile') {
          message = err.message
        } else {
          message = '发送失败，请稍后重试'
        }
        Toast(message)
      }
      this.isSendSmsLoading = false
    }
  }
}
</script>

<style lang='less' scoped>
.login-container {
  .send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #79B4FE;
      border: 0;
    }
    .van-button__text {
      font-size: 16px;
    }
  }
}
</style>
